<template>
  <a-layout style="min-height: 100vh">
    <a-layout-header>
      <div class="header">
        <div class="logo"><router-link to="/">个人博客与简历</router-link></div>
        <div class="nav">
          <router-link to="/">首页</router-link>
          <router-link to="/search">搜索</router-link>
          <router-link to="/categories">分类</router-link>
          <router-link to="/tags">标签</router-link>
          <router-link to="/archives">归档</router-link>
          <router-link to="/resume">简历</router-link>
          <a href="/api/articles/rss" target="_blank">RSS</a>
        </div>
        <div class="search">
          <a-input-search
            class="top-search"
            v-model:value="kw"
            placeholder="搜索文章、标签..."
            size="middle"
            :bordered="false"
            @search="goSearch"
            allow-clear
          />
        </div>
        <div class="user">
          <a-dropdown v-if="isAuthed && canManage">
            <a class="ant-dropdown-link" @click.prevent>管理</a>
            <template #overlay>
              <a-menu>
                <a-menu-item v-if="hasPerm('article:write') || hasPerm('article:update') || hasPerm('article:delete')"><router-link to="/admin/articles">文章</router-link></a-menu-item>
                <a-menu-item v-if="hasPerm('category:manage')"><router-link to="/admin/categories">分类</router-link></a-menu-item>
                <a-menu-item v-if="hasPerm('tag:manage')"><router-link to="/admin/tags">标签</router-link></a-menu-item>
                <a-menu-item v-if="hasPerm('comment:manage')"><router-link to="/admin/comments">评论</router-link></a-menu-item>
                <a-menu-item v-if="hasPerm('oss:manage')"><router-link to="/admin/oss">文件</router-link></a-menu-item>
                <a-menu-item v-if="hasPerm('role:manage')"><router-link to="/admin/roles">角色</router-link></a-menu-item>
                <a-menu-item v-if="hasPerm('permission:manage')"><router-link to="/admin/permissions">权限</router-link></a-menu-item>
                <a-menu-item v-if="hasPerm('user:manage')"><router-link to="/admin/users">用户管理</router-link></a-menu-item>
                <a-menu-item v-if="hasPerm('user:manage')"><router-link to="/admin/user-roles">用户角色</router-link></a-menu-item>
                <a-menu-item v-if="hasPerm('permission:manage')"><router-link to="/admin/oplogs">操作日志</router-link></a-menu-item>
                <a-menu-item v-if="hasPerm('user:manage')"><router-link to="/admin/sessions">在线用户</router-link></a-menu-item>
                <a-menu-item v-if="hasPerm('permission:manage')"><router-link to="/admin/settings">系统配置</router-link></a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
          <a v-if="!isAuthed" @click="openLogin">登录</a>
          <a-dropdown v-else>
            <a class="ant-dropdown-link" @click.prevent>
              <a-avatar v-if="avatarSrc" :src="avatarSrc" size="small" style="margin-right:8px" />
              <a-avatar v-else size="small" style="margin-right:8px">{{ displayInitial }}</a-avatar>
              {{ displayName }}
            </a>
            <template #overlay>
              <a-menu>
                <a-menu-item><router-link to="/profile">个人中心</router-link></a-menu-item>
                <a-menu-item @click="onLogout">退出登录</a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </div>
      </div>
    </a-layout-header>
    <a-layout-content style="padding: 24px">
      <router-view />
    </a-layout-content>
    <a-modal v-model:open="loginVisible" :title="isRegister ? '注册' : '登录'" :ok-text="isRegister ? '注册' : '登录'" @ok="onAuthOk">
      <a-form layout="vertical">
        <a-form-item label="用户名">
          <a-input v-model:value="username" />
        </a-form-item>
        <a-form-item v-if="isRegister" label="邮箱（可选）">
          <a-input v-model:value="email" />
        </a-form-item>
        <a-form-item label="密码">
          <a-input-password v-model:value="password" />
        </a-form-item>
        <div style="text-align:right">
          <a @click="toggleRegister">{{ isRegister ? '已有账号？去登录' : '没有账号？去注册' }}</a>
        </div>
      </a-form>
    </a-modal>
  </a-layout>
  
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { login, logout, getProfile, type UserProfileVO, register } from '@/api/admin'

const router = useRouter()
const kw = ref('')
const loginVisible = ref(false)
const username = ref('admin')
const password = ref('admin')
const email = ref('')
const isRegister = ref(false)
const isAuthed = ref<boolean>(!!localStorage.getItem('token'))
const profile = ref<UserProfileVO | null>(null)

const displayName = computed(() => (profile.value?.nickname || profile.value?.username || '用户'))
const displayInitial = computed(() => {
  const t = (profile.value?.nickname || profile.value?.username || 'U') as string
  return t ? t.slice(0, 1).toUpperCase() : 'U'
})
const avatarSrc = computed(() => {
  const src = profile.value?.avatar
  return src && src.trim() ? src : ''
})

const permSet = computed<Set<string>>(() => {
  const perms = profile.value?.perms || (localStorage.getItem('profile') ? (JSON.parse(localStorage.getItem('profile') as string).perms as string | undefined) : undefined)
  if (!perms) return new Set()
  return new Set((perms as string).split(',').map(s => s.trim()).filter(Boolean))
})
function hasPerm(code: string) { return permSet.value.has(code) }
const canManage = computed(() => hasPerm('article:write') || hasPerm('article:update') || hasPerm('article:delete') || hasPerm('category:manage') || hasPerm('tag:manage') || hasPerm('comment:manage') || hasPerm('resume:manage') || hasPerm('oss:manage') || hasPerm('user:manage') || hasPerm('role:manage') || hasPerm('permission:manage'))

function goSearch() {
  router.push({ name: 'SearchPage', query: { q: kw.value || undefined } })
}

function openLogin() {
  loginVisible.value = true
}

async function onLogin() {
  const resp = await login(username.value, password.value)
  const token = (resp.data as any)?.token
  if (token) {
    localStorage.setItem('token', token)
    loginVisible.value = false
    isAuthed.value = true
    await fetchProfile()
  }
}

async function onRegister() {
  if (!username.value || !password.value) return
  const resp = await register({ username: username.value, password: password.value, email: email.value || undefined })
  if ((resp as any).code === 0) {
    // 注册成功后直接登录
    await onLogin()
  }
}

function toggleRegister() {
  isRegister.value = !isRegister.value
}

async function onLogout() {
  await logout()
  localStorage.removeItem('token')
  isAuthed.value = false
  profile.value = null
  router.push({ path: '/' })
}

async function fetchProfile() {
  try {
    const resp = await getProfile()
    if ((resp as any).code === 0) profile.value = (resp as any).data
    try { localStorage.setItem('profile', JSON.stringify(profile.value)) } catch {}
  } catch {}
}

onMounted(() => {
  if (isAuthed.value) fetchProfile()
  window.addEventListener('profile:updated', handleProfileUpdated as any)
})

onUnmounted(() => {
  window.removeEventListener('profile:updated', handleProfileUpdated as any)
})

function handleProfileUpdated(e: CustomEvent) {
  const d: any = (e as any).detail || {}
  profile.value = { ...(profile.value || {} as any), ...d } as any
}

async function onAuthOk() {
  if (isRegister.value) await onRegister()
  else await onLogin()
}
</script>

<style scoped>
.header { display: flex; align-items: center; gap: 16px; color: #fff; }
.logo a { color: #fff; font-weight: bold; text-decoration: none; }
.nav { display: flex; gap: 12px; }
.nav a { color: #fff; text-decoration: none; }
.nav a.router-link-active { text-decoration: underline; }
.search { margin-left: auto; }
.top-search :deep(.ant-input-affix-wrapper) {
  background: rgba(255,255,255,0.16);
  border: 1px solid rgba(255,255,255,0.25);
  color: #fff;
  transition: all .2s ease;
  height: 36px;
  display: flex;
  align-items: center;
  line-height: 1;
}
.top-search :deep(.ant-input) { color: #fff; }
.top-search :deep(.ant-input::placeholder) { color: rgba(255,255,255,0.75); }
.top-search :deep(.ant-input-affix-wrapper:hover),
.top-search :deep(.ant-input-affix-wrapper-focused) {
  background: rgba(255,255,255,0.22);
  border-color: rgba(255,255,255,0.55);
  box-shadow: 0 0 0 2px rgba(24,144,255,0.2);
}
.user { display:flex; align-items:center; gap:12px; margin-left: 16px; }
</style>


